﻿using System;
namespace HB.Base
{
    /// <summary>
    /// 脉冲探测器
    /// </summary>
    public class PulseDetector
    {
        TriggerTimer timer = new TriggerTimer();
        double PulseThreshold { get; set; }
        bool isFiring { get; set; }
        /// <summary>
        /// 是否处于脉冲发射中
        /// </summary>
        public bool IsFiring
        {
            get => isFiring; set
            {
                if (value != isFiring)
                {
                    isFiring = value;
                    IsFiringChanged?.Invoke(value);
                }

            }
        }
        public event Action<bool> IsFiringChanged;
        bool ReadyToOutFire { get; set; }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pulseThreshold">判定脉冲的阈值</param>
        /// <param name="checkStateFrequency">检测周期（单次脉冲存活时间）</param>
        public PulseDetector(double pulseThreshold, double checkStateFrequency)
        {
            this.PulseThreshold = pulseThreshold;
            timer.Start(checkStateFrequency, (t, i) =>
            {
                if (ReadyToOutFire)
                {
                    IsFiring = false;
                }
                ReadyToOutFire = true;

            });
        }
        /// <summary>
        /// 记录此刻数据值，可高频调用
        /// </summary>
        /// <param name="currValue"></param>
        public void Log(double currValue)
        {
            if (!timer.IsRunning) { return; }
            if (currValue >= PulseThreshold)
            {
                IsFiring = true;
                ReadyToOutFire = false;
            }
        }
        /// <summary>
        /// 停止并释放探测器
        /// </summary>
        public void Stop()
        {
            timer.Stop();
        }
    }
}
